package com.whereta.controller.main;

import com.whereta.service.IMenuService;
import com.whereta.vo.MenuCreateVO;
import com.whereta.vo.MenuEditVO;
import com.whereta.vo.ResultVO;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by vincent on 15-8-31.
 */
@RequestMapping("/main/menu")
@Controller
public class MenuController {
    @Resource
    private IMenuService menuService;


    //菜单管理
    @RequestMapping("/manage")
    public String manageMenu() {
        return "main/menu/manage";
    }

    //创建菜单
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO createMenu(@Valid @ModelAttribute MenuCreateVO createVO, BindingResult bindingResult) {
        ResultVO resultVO = new ResultVO(true);
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        if (fieldErrors != null && !fieldErrors.isEmpty()) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            resultVO.setOk(false);
            resultVO.setMsg(defaultMessage);
            return resultVO;
        }

        resultVO = menuService.createMenu(createVO);

        return resultVO;
    }

    //编辑菜单
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO editMenu(@Valid @ModelAttribute MenuEditVO editVO, BindingResult bindingResult) {
        ResultVO resultVO = new ResultVO(true);
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        if (fieldErrors != null && !fieldErrors.isEmpty()) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            resultVO.setOk(false);
            resultVO.setMsg(defaultMessage);
            return resultVO;
        }

        resultVO = menuService.editMenu(editVO);

        return resultVO;
    }

    //删除菜单
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO delMenu(@RequestParam int id) {
        ResultVO resultVO = menuService.deleteMenu(id);
        return resultVO;
    }

    //菜单授权
    @RequestMapping(value = "/grant", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO grantMenuPermission(@RequestParam int id,@RequestParam(value = "peridArray[]",required = false) Integer []peridArray) {
        ResultVO resultVO = menuService.grantPermissions(id,peridArray);
        return resultVO;
    }

}
